package com.starpl.mobile.android.monthunsae.november.common;

import java.util.Calendar;
import java.util.Date;

import android.app.AlarmManager;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.starpl.mobile.android.platform.common.base.BaseApplication;

/**
 * 디바이스 자체의 로컬 푸시 구현을 위한 클래스
 * 
 * @author 박우람
 * @since 2011.03.18
 */
public class LocalPushClient
{
	private static final String TAG = "LocalPushClient";
	public static String PUSH_ALARM_ACTION;
	private Context mContext;
	private Calendar mCalendar;
	private AlarmManager mManager;
	
	/**
	 * 기본 생성자
	 */
	public LocalPushClient()
	{
		this.mContext = BaseApplication.getContext();
		this.mCalendar = Calendar.getInstance();
		this.mManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
		PUSH_ALARM_ACTION = BaseApplication.getConfigPersistent("pushIntent");
	}
	
	/**
	 * 새로운 푸시를 등록한다.
	 * 
	 * @param targetDate 목표가 되는 시각
	 * @param message 출력할 메시지
	 */
	public long setLocalPush(Date targetDate, String message)
	{
		Intent intent = new Intent(mContext, LocalPushReceiver.class);
		intent.setAction(PUSH_ALARM_ACTION);
		intent.putExtra("t", BaseApplication.getConfigPersistent("appsName"));
		intent.putExtra("m", message);
		intent.putExtra("p", PUSH_ALARM_ACTION);
		PendingIntent sender = PendingIntent.getBroadcast(mContext, targetDate.getDate(), intent, 0);
		
		mCalendar.setTime(targetDate);
		long pushMilliSecond = mCalendar.getTimeInMillis();
		
		mManager.set(AlarmManager.RTC_WAKEUP, pushMilliSecond, sender);
		Log.d(TAG, "새로운 푸시를 등록하였습니다: " + targetDate.toString());
		
		return pushMilliSecond;
	}
	
	/**
	 * 기존의 푸시를 제거한다.
	 * 
	 * @param targetDate 목표가 되는 시각
	 */
	public void removeLocalPush(Date targetDate)
	{
		Intent intent = new Intent();
		PendingIntent sender = PendingIntent.getBroadcast(mContext, targetDate.getDate(), intent, 0);
		mManager.cancel(sender);
		
		NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
		notificationManager.cancel(targetDate.getDate());
	}
}
